package com.example.beatbox;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.beatbox.databinding.FragmentBeatBoxBinding;
import com.example.beatbox.databinding.ListItemSoundBinding;

import java.util.List;

public class BeatBoxFragment extends Fragment {
 private  BeatBox mBeatBox;

 public  static BeatBoxFragment newInstance(){
     return new BeatBoxFragment();
 }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBeatBox=new BeatBox(getActivity());

    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        //return super.onCreateView(inflater, container, savedInstanceState);
        //不用findViewById去获取，而是使用数据绑定工具提供的方法获取视图
        FragmentBeatBoxBinding binding= DataBindingUtil.inflate(inflater,R.layout.fragment_beat_box,container,false);
        binding.recyclerView.setLayoutManager(new GridLayoutManager(getActivity(),3));
       // binding.recyclerView.setAdapter(new SoundAdapter());
        binding.recyclerView.setAdapter(new SoundAdapter(mBeatBox.getmSound()));
        return binding.getRoot();
    }
    private  class SoundHolder extends RecyclerView.ViewHolder{
     //在layout布局里面加了layout会自动生成对应的工具
     private ListItemSoundBinding mBinding;
     private  SoundHolder(ListItemSoundBinding binding){
         super(binding.getRoot());
         mBinding=binding;
         mBinding.setViewModel(new SoundViewModel(mBeatBox));
     }
     public  void  bind(Sound sound){
         mBinding.getViewModel().setmSound(sound);
         mBinding.executePendingBindings();
     }

    }

    private  class SoundAdapter extends RecyclerView.Adapter<SoundHolder>{
        private List<Sound> mSounds;
        @NonNull
        @Override
        public SoundHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
           // return null;
            LayoutInflater inflater=LayoutInflater.from(getActivity());
            ListItemSoundBinding binding=DataBindingUtil.inflate(inflater,R.layout.list_item_sound,parent,false);
            return new SoundHolder(binding);
        }
        public  SoundAdapter(List<Sound> sounds){
            mSounds=sounds;

        }

        @Override
        public void onBindViewHolder(@NonNull SoundHolder holder, int position) {
            Sound sound=mSounds.get(position);
            holder.bind(sound);
        }

        @Override
        public int getItemCount() {
           // return 0;
            return mSounds.size();
        }
    }
}

